// 声破天播放器 JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // 初始化播放器
    initPlayer();
    
    // 初始化播放按钮
    initPlayButton();
    
    // 初始化音量控制
    initVolumeControl();
    
    // 初始化进度条
    initProgressBar();
    
    // 初始化播放器操作按钮
    initPlayerButtons();
    
    // 初始化歌词功能
    initLyrics();
    
    // 更新时间显示
    updatePlayerTimeDisplay();
    
    // 初始化专辑封面点击事件
    initAlbumCoverClick();
});

// 初始化播放器
function initPlayer() {
    // 创建全局音频实例
    window.audioPlayer = new Audio('assets/music/qingtian.mp3');
    window.audioPlayer.volume = 0.7; // 默认音量70%
    
    // 当前播放状态
    window.playerState = {
        isPlaying: false, 
        currentTrack: {
            title: "晴天", 
            artist: "周杰伦",
            album: "叶惠美",
            cover: "assets/images/covers/cover2.jpg",
            duration: 269, // 4:29秒
            source: "assets/music/qingtian.mp3"
        }
    };

    // 设置动态背景
    const dynamicBg = document.querySelector('.dynamic-bg');
    if (dynamicBg) {
        dynamicBg.style.background = 'linear-gradient(45deg, #0f2972, #1a3b80, #264d8e)';
    }
    
    // 监听播放时间更新事件，用于更新进度条和歌词显示
    window.audioPlayer.addEventListener('timeupdate', function() {
        updateProgress();
        updateLyrics();
    });

    // 从localStorage恢复播放状态
    restorePlaybackFromLocalStorage();

    // 更新播放器显示
    updatePlayerDisplay();
    
    // 确保进度条初始状态正确
    updateProgress();
}

// 从localStorage恢复播放状态
function restorePlaybackFromLocalStorage() {
    // 恢复保存的播放时间
    const savedTime = localStorage.getItem('currentPlayTime');
    if (savedTime && !isNaN(parseFloat(savedTime))) {
        window.audioPlayer.currentTime = parseFloat(savedTime);
    }
    
    // 恢复保存的音量设置
    const savedVolume = localStorage.getItem('currentVolume');
    if (savedVolume && !isNaN(parseFloat(savedVolume))) {
        window.audioPlayer.volume = parseFloat(savedVolume);
    }
    
    // 恢复静音状态
    const wasMuted = localStorage.getItem('isMuted');
    if (wasMuted === 'true') {
        window.audioPlayer.muted = true;
    }
    
    // 检查URL参数是否包含时间信息（这会覆盖localStorage中的时间）
    const urlParams = new URLSearchParams(window.location.search);
    const startTime = urlParams.get('time');
    
    // 如果有时间参数，设置播放起始位置
    if (startTime && !isNaN(parseFloat(startTime))) {
        window.audioPlayer.currentTime = parseFloat(startTime);
        console.log(`设置播放起始位置: ${startTime}秒`);
    }
    
    // 恢复播放状态
    if (localStorage.getItem('wasPlaying') === 'true') {
        // 尝试恢复播放但处理可能的错误（浏览器可能阻止自动播放）
        window.audioPlayer.play().catch(e => {
            console.log("自动播放失败，需要用户交互:", e);
        });
        window.playerState.isPlaying = true;
    }
}

// 更新播放器显示信息
function updatePlayerDisplay() {
    const track = window.playerState.currentTrack;
    
    // 更新标题
    document.title = `${track.title} - ${track.artist} | 声破天`;
    
    // 更新专辑封面
    const albumCover = document.querySelector('.album-cover img');
    if (albumCover) albumCover.src = track.cover;
    
    // 更新歌曲信息
    const songTitle = document.querySelector('.lyrics-header .song-info h1');
    const artistName = document.querySelector('.lyrics-header .song-info h2');
    const albumName = document.querySelector('.lyrics-header .song-info .album-name');
    
    if (songTitle) songTitle.textContent = track.title;
    if (artistName) artistName.textContent = track.artist;
    if (albumName) albumName.textContent = `专辑：${track.album}`;
    
    // 更新底部播放器信息
    const smallTrackName = document.querySelector('.track-name');
    const smallArtistName = document.querySelector('.artist-name');
    const smallCover = document.querySelector('.track-image img');
    const totalTime = document.querySelector('.total-time');
    
    if (smallTrackName) smallTrackName.textContent = track.title;
    if (smallArtistName) smallArtistName.textContent = `${track.artist} - ${track.album}`;
    if (smallCover) smallCover.src = track.cover;
    if (totalTime) totalTime.textContent = formatTime(track.duration);
    
    // 更新播放按钮状态
    updatePlayButton(window.playerState.isPlaying);
}

// 初始化播放按钮
function initPlayButton() {
    const playButton = document.querySelector('.play-btn');
    if (!playButton) return;
    
    // 根据初始状态设置按钮
    updatePlayButton(window.playerState.isPlaying);
    
    // 添加点击事件
    playButton.addEventListener('click', function() {
        togglePlayState();
    });
}

// 更新播放按钮状态
function updatePlayButton(isPlaying) {
    const playBtn = document.querySelector('.play-btn');
    if (!playBtn) return;
    
    if (isPlaying) {
        playBtn.innerHTML = '<i class="fas fa-pause"></i>';
    } else {
        playBtn.innerHTML = '<i class="fas fa-play"></i>';
    }
}

// 切换播放状态
function togglePlayState() {
    const isPlaying = window.playerState.isPlaying;
    
    if (isPlaying) {
        // 当前正在播放，暂停
        window.audioPlayer.pause();
        window.playerState.isPlaying = false;
    } else {
        // 当前已暂停，开始播放
        window.audioPlayer.play();
        window.playerState.isPlaying = true;
    }
    
    // 更新播放按钮状态
    updatePlayButton(!isPlaying);
}

// 初始化歌词功能
function initLyrics() {
    // 载入完整歌词
    loadFullLyrics();
    
    // 设置用户交互
    setupLyricsInteraction();
}

// 加载完整歌词
function loadFullLyrics() {
    const lyrics = document.querySelector('.lyrics');
    if (!lyrics) return;
    
    // 完整的LRC歌词内容
    const lrcContent = `
[00:00.00]晴天 - 周杰伦 (Jay Chou)
[00:02.00]词：周杰伦
[00:04.00]曲：周杰伦
[00:06.00]编曲：周杰伦
[00:09.00]制作人：周杰伦
[00:11.00]合声：周杰伦
[00:13.00]合声编写：周杰伦
[00:15.00]吉他：蔡科俊Again
[00:18.00]贝斯：陈任佑
[00:20.00]鼓：陈柏州
[00:22.00]录音助理：刘勇志
[00:24.00]录音工程：杨瑞代（Alfa Studio）
[00:27.00]混音工程：杨大纬（杨大纬录音工作室）
[00:29.00]故事的小黄花
[00:32.00]从出生那年就飘着
[00:36.00]童年的荡秋千
[00:39.00]随记忆一直晃到现在
[00:42.00]Re So So Si Do Si La 
[00:45.00]So La Si Si Si Si La Si La So 
[00:49.00]吹着前奏望着天空
[00:53.00]我想起花瓣试着掉落
[00:56.00]为你翘课的那一天
[00:58.00]花落的那一天
[01:00.00]教室的那一间
[01:02.00]我怎么看不见
[01:04.00]消失的下雨天
[01:05.00]我好想再淋一遍
[01:09.00]没想到失去的勇气我还留着
[01:16.00]好想再问一遍
[01:17.00]你会等待还是离开
[01:24.00]刮风这天我试过握着你手
[01:30.00]但偏偏雨渐渐大到我看你不见
[01:38.00]还要多久我才能在你身边
[01:45.00]等到放晴的那天也许我会比较好一点
[01:52.00]从前从前有个人爱你很久
[01:58.00]但偏偏风渐渐把距离吹得好远
[02:06.00]好不容易又能再多爱一天
[02:13.00]但故事的最后你好像还是说了拜拜
[02:34.00]为你翘课的那一天
[02:36.00]花落的那一天
[02:38.00]教室的那一间
[02:40.00]我怎么看不见
[02:42.00]消失的下雨天
[02:43.00]我好想再淋一遍
[02:48.00]没想到失去的勇气我还留着
[02:54.00]好想再问一遍
[02:56.00]你会等待还是离开
[03:02.00]刮风这天我试过握着你手
[03:08.00]但偏偏雨渐渐大到我看你不见
[03:16.00]还要多久我才能在你身边
[03:23.00]等到放晴的那天也许我会比较好一点
[03:30.00]从前从前有个人爱你很久
[03:37.00]偏偏风渐渐把距离吹得好远
[03:44.00]好不容易又能再多爱一天
[03:51.00]但故事的最后你好像还是说了拜拜
[03:58.00]刮风这天我试过握着你手
[04:01.00]但偏偏雨渐渐大到我看你不见
[04:05.00]还要多久我才能够在你身边
[04:09.00]等到放晴那天也许我会比较好一点
[04:12.00]从前从前有个人爱你很久
[04:15.00]但偏偏雨渐渐把距离吹得好远
[04:19.00]好不容易又能再多爱一天
[04:22.00]但故事的最后你好像还是说了拜拜`;

    // 解析LRC歌词
    const parsedLyrics = parseLRC(lrcContent);
    
    // 生成HTML
    let lyricsHTML = `<div style="height: 40px;"></div>`;
    
    parsedLyrics.forEach(line => {
        lyricsHTML += `<p class="lyric-line" data-time="${line.time}">${line.text}</p>`;
    });
    
    lyricsHTML += `<div style="height: 180px;"></div>`;
    
    // 更新歌词内容
    lyrics.innerHTML = lyricsHTML;
    
    // 保存解析后的歌词供后续使用
    window.parsedLyrics = parsedLyrics;

    // 更新歌词提示
    const scrollHintContainer = document.querySelector('.scroll-hint-container');
    if (scrollHintContainer) {
        scrollHintContainer.innerHTML = `⬆️ 共 ${parsedLyrics.length} 行歌词，点击歌词可跳转 ⬇️`;
        scrollHintContainer.style.padding = '8px';
        scrollHintContainer.style.backgroundColor = 'rgba(29, 185, 84, 0.15)';
        scrollHintContainer.style.borderRadius = '20px';
        scrollHintContainer.style.margin = '10px 0';
    }
}

// 解析LRC歌词
function parseLRC(lrcContent) {
    const lines = lrcContent.trim().split('\n');
    const result = [];
    
    // LRC时间标签正则表达式
    const timeRegex = /\[(\d{2}):(\d{2})\.(\d{2})\]/;
    
    lines.forEach(line => {
        const match = timeRegex.exec(line);
        if (match) {
            const minutes = parseInt(match[1], 10);
            const seconds = parseInt(match[2], 10);
            const centiseconds = parseInt(match[3], 10);
            
            // 计算总秒数
            const time = minutes * 60 + seconds + centiseconds / 100;
            
            // 提取歌词文本（去掉时间标签）
            const text = line.replace(timeRegex, '').trim();
            
            result.push({
                time: time,
                text: text
            });
        }
    });
    
    // 按时间排序
    return result.sort((a, b) => a.time - b.time);
}

// 设置歌词交互功能
function setupLyricsInteraction() {
    const lyricsContainer = document.querySelector('.lyrics-container');
    if (!lyricsContainer) return;
    
    // 监听用户滚动
    lyricsContainer.addEventListener('scroll', function() {
        // 记录用户最后一次滚动时间
        window.lastUserScrollTime = Date.now();
    });
    
    // 点击歌词行跳转到对应时间
    lyricsContainer.addEventListener('click', function(e) {
        if (e.target.classList.contains('lyric-line')) {
            const time = parseFloat(e.target.dataset.time || "0");
            if (window.audioPlayer && !isNaN(time)) {
                window.audioPlayer.currentTime = time;
                window.lastUserScrollTime = Date.now();
            }
        }
    });
}

// 更新歌词显示
function updateLyrics() {
    if (!window.audioPlayer) return;
    
    const currentTime = window.audioPlayer.currentTime;
    const lines = document.querySelectorAll('.lyric-line');
    if (lines.length === 0) return;
    
    // 移除所有活跃状态
    lines.forEach(line => line.classList.remove('active'));
    
    // 找到当前应该高亮的行
    let activeLine = null;
    for (let i = 0; i < lines.length; i++) {
        const time = parseFloat(lines[i].dataset.time || "0");
        const nextTime = i < lines.length - 1 ? parseFloat(lines[i + 1].dataset.time || "999999") : 999999;
        
        if (currentTime >= time && currentTime < nextTime) {
            activeLine = lines[i];
            break;
        }
    }
    
    // 如果没找到活跃行但有歌词，查找最接近当前时间的歌词行
    if (!activeLine && lines.length > 0) {
        let lastActiveTime = 0;
        
        for (let i = 0; i < lines.length; i++) {
            const time = parseFloat(lines[i].dataset.time || "0");
            if (time <= currentTime && time >= lastActiveTime) {
                lastActiveTime = time;
                activeLine = lines[i];
            }
        }
    }
    
    // 添加活跃状态并滚动到该行
    if (activeLine) {
        activeLine.classList.add('active');
        
        // 如果用户在过去2秒内没有手动滚动，则自动滚动
        if (!window.lastUserScrollTime || (Date.now() - window.lastUserScrollTime > 2000)) {
            scrollToActiveLyric(activeLine);
        }
    }
}

// 滚动到当前活跃歌词
function scrollToActiveLyric(activeLine) {
    if (!activeLine) return;
    
    const container = document.querySelector('.lyrics-container');
    if (!container) return;
    
    // 计算应该滚动到的位置，使活跃行位于容器1/3处
    const containerHeight = container.clientHeight;
    const lineTop = activeLine.offsetTop;
    const lineHeight = activeLine.clientHeight;
    const scrollTo = lineTop - (containerHeight / 3) + (lineHeight / 2);
    
    // 平滑滚动到该位置
    container.scrollTo({
        top: Math.max(0, scrollTo),
        behavior: 'smooth'
    });
}

// 初始化音量控制
function initVolumeControl() {
    const volumeControl = document.querySelector('.volume-control');
    const volumeBar = document.querySelector('.volume-bar');
    const volumeLevel = document.querySelector('.volume-level');
    const volumeHandle = document.querySelector('.volume-handle');
    const volumeBtn = document.querySelector('.volume-control .option-btn');
    
    if (!volumeBar || !volumeLevel || !volumeHandle || !volumeBtn) return;
    
    let previousVolume = window.audioPlayer.volume;
    
    // 恢复保存的音量UI状态
    const savedVolume = localStorage.getItem('currentVolume');
    if (savedVolume && !isNaN(parseFloat(savedVolume))) {
        const volume = parseFloat(savedVolume);
        
        // 如果之前是静音状态，显示静音UI
        const wasMuted = localStorage.getItem('isMuted') === 'true';
        updateVolumeUI(wasMuted ? 0 : volume);
        
        previousVolume = volume;
    } else {
        // 使用默认音量
        updateVolumeUI(window.audioPlayer.volume);
    }
    
    // 音量按钮点击事件（静音/取消静音）
    volumeBtn.addEventListener('click', function() {
        if (window.audioPlayer.muted || window.audioPlayer.volume === 0) {
            // 当前已静音，恢复音量
            window.audioPlayer.muted = false;
            window.audioPlayer.volume = previousVolume > 0 ? previousVolume : 0.7;
            updateVolumeUI(window.audioPlayer.volume);
            
            // 保存状态到localStorage
            localStorage.setItem('isMuted', 'false');
            localStorage.setItem('currentVolume', window.audioPlayer.volume.toString());
        } else {
            // 当前有音量，需要静音
            previousVolume = window.audioPlayer.volume;
            window.audioPlayer.muted = true;
            updateVolumeUI(0);
            
            // 保存状态到localStorage
            localStorage.setItem('isMuted', 'true');
            localStorage.setItem('currentVolume', previousVolume.toString());
        }
    });
    
    // 音量条点击事件
    volumeBar.addEventListener('click', function(e) {
        const rect = this.getBoundingClientRect();
        const clickPosition = e.clientX - rect.left;
        const newVolume = Math.max(0, Math.min(1, clickPosition / rect.width));
        
        window.audioPlayer.volume = newVolume;
        window.audioPlayer.muted = (newVolume === 0);
        previousVolume = newVolume > 0 ? newVolume : previousVolume;
        updateVolumeUI(newVolume);
        
        // 保存状态到localStorage
        localStorage.setItem('currentVolume', newVolume.toString());
        localStorage.setItem('isMuted', (newVolume === 0).toString());
    });
}

// 更新音量UI
function updateVolumeUI(volume) {
    volume = Math.max(0, Math.min(1, volume));
    const percent = volume * 100;
    
    const volumeLevel = document.querySelector('.volume-level');
    const volumeHandle = document.querySelector('.volume-handle');
    const volumeBtn = document.querySelector('.volume-control .option-btn i');
    
    if (volumeLevel) volumeLevel.style.width = `${percent}%`;
    if (volumeHandle) volumeHandle.style.left = `${percent}%`;
    
    if (volumeBtn) {
        if (volume === 0 || (window.audioPlayer && window.audioPlayer.muted)) {
            volumeBtn.className = 'fas fa-volume-mute';
        } else if (volume < 0.5) {
            volumeBtn.className = 'fas fa-volume-down';
        } else {
            volumeBtn.className = 'fas fa-volume-up';
        }
    }
}

// 初始化进度条
function initProgressBar() {
    const progressBar = document.querySelector('.progress-bar');
    const progress = document.querySelector('.progress');
    const progressHandle = document.querySelector('.progress-handle');
    const currentTimeEl = document.querySelector('.current-time');
    
    if (!progressBar || !progress || !progressHandle || !currentTimeEl) return;
    
    // 确保进度条初始状态正确
    if (window.audioPlayer) {
        if (window.audioPlayer.currentTime > 0 && window.audioPlayer.duration) {
            // 有播放时间，设置对应的进度
            const ratio = window.audioPlayer.currentTime / window.audioPlayer.duration;
            updateProgressUI(ratio);
        } else {
            // 无播放时间或播放时间为0，进度条归零
            updateProgressUI(0);
        }
    } else {
        // 没有播放器实例，进度条归零
        updateProgressUI(0);
    }
    
    // 进度条点击事件
    progressBar.addEventListener('click', function(e) {
        const rect = this.getBoundingClientRect();
        const clickPosition = e.clientX - rect.left;
        const ratio = clickPosition / rect.width;
        
        if (window.audioPlayer && window.audioPlayer.duration) {
            window.audioPlayer.currentTime = ratio * window.audioPlayer.duration;
            updateProgressUI(ratio);
            
            // 保存当前播放位置到localStorage
            localStorage.setItem('currentPlayTime', window.audioPlayer.currentTime.toString());
        }
    });
}

// 更新进度条UI
function updateProgressUI(ratio) {
    // 确保时间为0时进度条也是0
    ratio = (ratio <= 0 || isNaN(ratio)) ? 0 : Math.min(1, ratio);
    const percent = ratio * 100;
    
    const progress = document.querySelector('.progress');
    const progressHandle = document.querySelector('.progress-handle');
    
    if (progress) progress.style.width = `${percent}%`;
    if (progressHandle) progressHandle.style.left = `${percent}%`;
}

// 更新播放进度
function updateProgress() {
    if (!window.audioPlayer) return;
    
    // 计算进度比例，确保有效的duration
    let progressRatio = 0;
    if (window.audioPlayer.duration && window.audioPlayer.duration > 0) {
        progressRatio = window.audioPlayer.currentTime / window.audioPlayer.duration;
    }
    
    // 更新进度条UI
    updateProgressUI(progressRatio);
    
    // 更新时间显示
    const currentTimeDisplay = document.querySelector('.current-time');
    if (currentTimeDisplay) {
        currentTimeDisplay.textContent = formatTime(window.audioPlayer.currentTime);
    }
}

// 初始化播放器操作按钮
function initPlayerButtons() {
    // 上一首按钮
    const prevButton = document.querySelector('.control-buttons .control-btn:nth-child(2)');
    if (prevButton) {
        prevButton.addEventListener('click', function() {
            // 本示例中重新开始播放当前歌曲
            window.audioPlayer.currentTime = 0;
        });
    }
    
    // 下一首按钮
    const nextButton = document.querySelector('.control-buttons .control-btn:nth-child(4)');
    if (nextButton) {
        nextButton.addEventListener('click', function() {
            // 本示例中重新开始播放当前歌曲
            window.audioPlayer.currentTime = 0;
        });
    }
    
    // 随机播放按钮
    const shuffleButton = document.querySelector('.control-buttons .control-btn:first-child');
    if (shuffleButton) {
        shuffleButton.addEventListener('click', function() {
            this.classList.toggle('active');
        });
    }
    
    // 循环播放按钮
    const repeatButton = document.querySelector('.control-buttons .control-btn:last-child');
    if (repeatButton) {
        repeatButton.addEventListener('click', function() {
            this.classList.toggle('active');
        });
    }
    
    // 收藏按钮
    const likeButton = document.querySelector('.track-actions .action-btn:first-child');
    if (likeButton) {
        likeButton.addEventListener('click', function() {
            this.innerHTML = this.innerHTML.includes('far') ? 
                '<i class="fas fa-heart"></i>' : 
                '<i class="far fa-heart"></i>';
        });
    }
}

// 初始化专辑封面点击事件
function initAlbumCoverClick() {
    // 获取底部播放器的专辑图片元素
    const albumCoverElement = document.querySelector('.track-image');
    
    if (albumCoverElement) {
        // 添加点击事件
        albumCoverElement.addEventListener('click', function() {
            togglePlayerView();
        });
        
        // 添加鼠标悬停样式，提示可点击
        albumCoverElement.style.cursor = 'pointer';
        albumCoverElement.title = '点击切换歌词视图';
    }
}

// 切换播放器视图
function togglePlayerView() {
    // 检查当前是否在播放器页面
    const isPlayerPage = window.location.pathname.includes('player.html');
    
    if (isPlayerPage) {
        // 如果当前在播放器页面，返回上一页
        console.log('从播放器页面返回上一个页面');
        window.history.back();
    } else {
        // 如果当前不在播放器页面，跳转到播放器页面
        console.log('跳转到播放器页面显示歌词');
        
        // 获取当前播放的歌曲信息
        const currentTrack = window.playerState ? window.playerState.currentTrack : null;
        
        if (currentTrack) {
            // 构建URL参数
            const params = new URLSearchParams();
            params.append('name', currentTrack.title);
            params.append('artist', currentTrack.artist);
            params.append('album', currentTrack.album);
            params.append('type', 'track');
            params.append('time', window.audioPlayer ? window.audioPlayer.currentTime : 0);
            
            // 如果有封面图片，也添加到参数中
            if (currentTrack.cover) {
                params.append('image', currentTrack.cover);
            }
            
            // 跳转到播放器页面
        } else {
            // 如果没有当前播放的歌曲信息，使用默认参数
            window.location.href = 'player.html?name=晴天&artist=周杰伦&type=track';
        }
    }
}

// 更新播放器时间显示
function updatePlayerTimeDisplay() {
    const currentTimeEl = document.querySelector('.current-time');
    const totalTimeEl = document.querySelector('.total-time');
    
    if (currentTimeEl && totalTimeEl) {
        // 设置初始显示
        currentTimeEl.textContent = "0:00";
        totalTimeEl.textContent = formatTime(window.playerState.currentTrack.duration);
        
        // 添加平滑过渡效果
        const progressBar = document.querySelector('.progress');
        const progressHandle = document.querySelector('.progress-handle');
        
        if (progressBar) progressBar.style.transition = 'width 0.1s linear';
        if (progressHandle) progressHandle.style.transition = 'left 0.1s linear';
    }
}

// 格式化时间（秒 -> MM:SS）
function formatTime(seconds) {
    if (isNaN(seconds)) return "0:00";
    
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs < 10 ? '0' + secs : secs}`;
}